package lock

import java.util.concurrent.locks.ReentrantLock

/**
 * 公平锁与非公平锁的简单示例
 */
class Fair {
    //公平锁
    private val lock = ReentrantLock(true)

    fun test() {
        println("Thread = " + Thread.currentThread().name + " waiting")

        try {
            lock.lock()
            println("Thread = " + Thread.currentThread().name + " get")
            Thread.sleep(100)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            lock.unlock()
        }
    }
}

class NotFair {
    //非公平锁
    private val lock = ReentrantLock()

    fun test() {
        println("Thread = " + Thread.currentThread().name + " waiting")

        try {
            lock.lock()
            println("Thread = " + Thread.currentThread().name + " get")
            Thread.sleep(100)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            lock.unlock()
        }

    }
}

fun main() {
    val fair = Fair()
    val notFair = NotFair()

    println("fair start")
    for (index in 1..10) {
        val thread = Thread({
            fair.test()
        }, "thread-$index")
        thread.start()
    }

    Thread.sleep(20000)

    println("notFair start")
    for (index in 1..10) {
        val thread = Thread({
            notFair.test()
        }, "thread-notFair-$index")
        thread.start()
    }

    //示例从结果上看公平锁与非公平锁没什么区别
}